/* XXXX
var ajxv = -1;
function setAjaxValue(data) {
    ajxv = data;
}*/

var map = {}

function makeTeamPage(teamid,userid) {    
    document.write('<form action="ActionDispatch" method=post >');
    document.write('<div>Sessions/week &nbsp;');
    document.write('<input class=ssw_topEvent id=sess type=radio name=_sessions[] value=1 sswindex=1 rowId=0 >One</input><span>&nbsp;&nbsp;</span>');
    document.write('<input class=ssw_topEvent id=sess type=radio name=_sessions[] value=2 sswindex=2 rowId=0 >Two</input><span>&nbsp;&nbsp;</span>');
    document.write('<input class=ssw_topEvent id=sess type=radio name=_sessions[] value=3 sswindex=3 rowId=0 >Three</input><span>&nbsp;&nbsp;</span>');
    document.write(' &nbsp;&nbsp; | &nbsp;&nbsp;Start date <input type=text class=ssw_topEvent name=_startdate[] id=ssw_datepicker rowId=0 ></input>');    
    document.write('</div><hr>');
    $( "#ssw_datepicker" ).datepicker();    
    dynamicRows("Ajx");
    document.write('<table><tr>');
    for (i =0; i <= 3; i++) {
        document.write('<td><div id=ssw_menuData_'+i+' rowiId='+i+' ><div style="background:#dde" ><p> &nbsp;</p><p> &nbsp;</p></div></div></td>');
    }
    document.write('</tr></table>');
    document.write('<p><div id=ssw_submit><button type=button id=ssw_submit >Submit request</button></div></p>');    
    document.write('<input type=hidden name=_teamId value='+teamid+' >');
    document.write('<input type=hidden name=_userId value='+userid+' >');
    document.write('<input type=hidden name=action value=SubmitRequest ></form>');
}

function dynamicRows(ajax) {
    var howMany = 0; // This should be an array
    for (rowId = 1; rowId <= 2; rowId++) {
        howMany = dynamicMenus(ajax,rowId);
    }
    listenToMenuChange(ajax,howMany);
}

function uncheckedBox(rowId,ckd) {
    return '<input '+ckd+' rowId='+rowId+
           ' id=ssw_menuEnabler_'+rowId+' type="checkbox" name="_choice'+rowId+'"[]" sswindex='+rowId+
           ' value='+rowId+' >Choice'+rowId+'</input>';
}

function dynamicMenus(ajax,rowId) {
    /* XXX 
    // Get num of menus from the server.
    $.ajax({
         url:     ajax+'?op=nummenus',
         success: function(data) {setAjaxValue(data);},
         async:   false
    });    
    howMany = parseInt(ajxv) - 1; // the zero element does not count.
    */
    // XXXXXXXXX
    var howMany = 6; // big enough?
    var ckd = '';
    if (rowId == 1) {
        ckd = ' checked="checked" ';
    }
    document.write('<div><table><tr>');
    document.write('<td><div id=ssw_menuEnabler_'+rowId+' rowId='+rowId+' >'+uncheckedBox(rowId,ckd)+'</div></td>');
    document.write('<td>'+scratchMenuRow(rowId)+'</td>');    
    $('div#ssw_menuContainer_'+rowId).html(emptyMenus(howMany,rowId));
    if (ckd != "") {
        $("div[rowId="+rowId+"][menuid=1]").load(ajax+"?op=menu&menuid=1&rowid="+rowId);
    }
    document.write('</tr></table></div><hr>');    
    return howMany; 
}

function scratchMenuRow(rowId) {
    return '<div rowId='+rowId+' id=ssw_menuContainer_'+rowId+' > </div>';
}

function emptyMenu(rowId,n) {
    var y = "<div class=ssw_event rowId="+rowId+" menuId="+n+" >";
    y += ' <p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>';
    y += "</div>";
    return y;
}

function emptyMenus(howMany,rowId) {
    var y = '';
    y += "<table><tr>";
    for (n=1;n<=howMany;n++) {
        y += "<td style='width:96;border:solid #eee 1px'>";
        y += emptyMenu(rowId,n);
        y += "</td>";
    }
    y += '</tr></table>';
    return y;
}

function map2string(map) {
    var y = '';
    var labels =  map['labels'];
    for (var i in labels) {
        var l = labels[i][0];
        if (typeof l == "undefined") {
            continue;
        }
        l = l.replace(' ','+');
        y += '&'+ i + '=' + l;
    }
    return y;
}

function listenToMenuChange(ajax,howMany) {    
    map = {}
    $('body').on("change", ".ssw_topEvent", function() {
        var id = $(this).attr('id');
        var val = $(this).attr("value");
        var map = collectData(0, -1);
    });
    $('body').on("change", "input[id^=ssw_menuEnabler_]", function() {
        var className = $(this).attr("class");
        var id = $(this).attr("id");
        var rowId = $(this).attr('rowId');
        for (x = Number(rowId)+1; x < rowId+99; x++) {
            $('div#ssw_menuContainer_'+x).html(emptyMenus(howMany,x));
            $('div#ssw_menuEnabler_'+x).html(uncheckedBox(x,''));
        }
        $('div#ssw_menuContainer_'+rowId).html(emptyMenus(howMany,rowId));
        if ($(this).attr("checked") == "checked") {
            if (rowId == '1' || $("input[id^=ssw_menuEnabler_"+(Number(rowId)-1)+"]").attr('checked') == 'checked') {
                $("div[rowId="+rowId+"][menuid=1]").load(ajax+"?op=menu&menuid=1&rowid="+rowId);
            } else {
                $('div#ssw_menuEnabler_'+rowId).html(uncheckedBox(rowId,''));
                alert('You need to complete the other choices first');
            }
        }
    });
    $('body').on("change", ".ssw_event", function() {
        var id = $(this).attr("id");
        var rowId = $(this).attr("rowId");
        var menuId = $(this).attr("menuId");
        var className = $(this).attr("class");
        // Selections so far are needed to determine next list of options.
        // XXXX map = 
        map = collectData(rowId, menuId);
        var mapargs = map2string(map);
        // Reset next menu to the right.
        NextMenuId = Number(menuId)+1;
        $("div.ssw_event[rowid="+rowId+"][menuid="+NextMenuId+"]").load(
        ajax+"?op=menu&menuid="+NextMenuId+"&rowid="+rowId+mapargs);
        // Remove all other menus.        
        for (j=NextMenuId+1;j<=howMany;j++) {
            $("div.ssw_event[rowid="+rowId+'][menuid='+j+']').html(emptyMenu(rowId,j));
        }        
        //map = collectData(rowId, menuId);
    });   
    $('body').on("click", "button#ssw_submit", function() {
        $('div#ssw_submit').html(
            '<button type=button disabled=disabled >Submit Request</button>'+
            '<input type="submit" value="CONFIRM REQUEST?" />'+
            '<button type=button onclick=\'window.location.href="/fm2/ManageTeams"\' >No. Never mind</button>');
    });
    $('form').submit(function() {
        // map[0] = 
        map = collectData(0, -1);
        // map[1] = collectData(1, -1);
        // map[2] = collectData(2, -1);
        //sure = false;
        //while (!sure) {
        /*
        if (confirm('Confirm?')) {
            if (confirm('Are you sure?')) {
                alert('Your request will be submitted');
                return true;
            }
        }*/
        return true;
    });
}

function collectData(rowId, menuId) { 
    // -1 stands for 'show them all'
    if (menuId < 0) {
        menuId = 9999;
    }
    var inputs = $("form :input[rowId="+rowId+"]");    
    // First create array of selected entries for each menu.
    var indices = new Array();
    var values  = new Array();
    var labels  = new Array();
    $.map(inputs, function(n, i) {
        values [n.name] = new Array();
        labels [n.name] = new Array();
        indices[n.name] = new Array();
    });
    // Then fill the arrays.
    var obj = $.map(inputs, function(n, i) {
        if (n.type == "submit") {
            return;
        }
        if (n.type == "radio" || n.type == "checkbox") {
            if ($(n).attr("checked")) {
                values [n.name].push(n.value);
                indices[n.name].push(n.getAttribute('sswindex'));
                var thetext = n.value;
                var intxt = $("input[name='"+n.name+"'][value='"+n.value+"']").get(0);
                if (intxt.nextSibling) {
                    thetext = intxt.nextSibling.nodeValue;
                }
                labels[n.name].push(thetext);
            }
        }         
        else if (n.type == "select-multiple") {
            $(n).find(":selected").each(function() {
                indices[n.name].push($(this).getAttribute('sswindex'));
                values [n.name].push($(this).val());
                labels [n.name].push($(this).text());
            });           
        } 
        else {
            var theval = n.value;
            var sswindex = $(n).find("option[value='"+theval+"']").attr('sswindex');
            if (typeof sswindex == "undefined") {
                sswindex = 0;
            }
            indices[n.name].push(sswindex);
            values[n.name].push(theval); 
            thetext = $(n).find("option[value='"+theval+"']").text();
            labels[n.name].push(thetext);
        }
    });
    // Display in document.
    var y = "<div style='background:#dde' ><p>";
    var c = 1;
    for (var i in indices) {
        c += 1;
        if ((c-2) <= menuId) {
            y += i;
            y += " ";
            var line = indices[i];
            var texl = labels [i];
            var valu = values [i];
            for (var j in line) {
                var e = line[j];
                var t = texl[j];
                var i = valu[j];
                y += "(" + e + ", " + i + ")" + t + " ";
            }                
            y += "</br>";
        }
    }
    y += '</p></div>';
    $('#ssw_menuData_'+rowId).html(y);
    var map = {}
    map["values"] = values;
    map["labels"] = labels;
    return map;
}
/*
function askConfirm() {
    var r = confirm("Confirm your choice ?");
    return r;
}
*/